through = require 'through2'
gutil = require 'gulp-util'
html2js = require 'html2js'
PluginError = gutil.PluginError

PLUGIN_NAME = 'gulp-html2js-ext'

# 将Buffer转换为gulp流
pluginStream = (contBuf) ->
  stream = through()
  stream.write contBuf
  stream

# 将HTML转换为CMD模块化的JS
gulp_html2js_ext = (_options) ->

  if not _options
    throw new PluginError PLUGIN_NAME, 'Missing html options!'

  # _options = new Buffer _options

  return through.obj (file, encoding, callback) ->

    if file.isNull()
      return callback null, file

    html = html2js file.contents.toString('utf8'), {mode: 'default', wrap: 'commonjs'}
    tmpljs = "(function(){define(function(require,exports,module){return #{html}});}).call(this);"

    # 将字符串转换为Buffer
    contBuf = new Buffer tmpljs

    # 如果文件是Buffer，则直接返回文件内容的Buffer
    if file.isBuffer()
      file.contents = contBuf

    # 如果文件是Stream，则先将文件内容的由Buffer转为Stream
    if file.isStream()
      file.contents = file.contents.pipe pluginStream contBuf

    return callback null, file

module.exports = gulp_html2js_ext